﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class GameObjectEx {

    public static T AddComponentEx<T> (this GameObject gameObject) where T : UnityEngine.Component {
        T t = gameObject.GetComponent<T> ();
        if (t != null)
            return t;
        return gameObject.AddComponent<T> ();
    }

    public static void SetScale (this GameObject gameObject, float val) {
        gameObject.transform.localScale = Vector3.one * val;
    }

    public static void SetTransformFormTarget (this GameObject gameObject, Transform target) {
        if (target == null)
            return;

        gameObject.transform.position = target.position;
        gameObject.transform.rotation = target.rotation;
        gameObject.transform.localScale = target.localScale;
    }

    public static void ResetTransformForLocal (this GameObject gameObject) {
        gameObject.transform.localPosition = Vector3.zero;
        gameObject.transform.localRotation = Quaternion.identity;
        gameObject.transform.localScale = Vector3.one;
    }

    public static void ResetTransform (this GameObject gameObject) {
        gameObject.transform.position = Vector3.zero;
        gameObject.transform.rotation = Quaternion.identity;
        gameObject.transform.localScale = Vector3.one;
    }

    public static void SetLayer (this GameObject gameObject, int layer, bool activeChild = true) {
        gameObject.layer = layer;

        if (activeChild) {
            Transform[] array = gameObject.GetComponentsInChildren<Transform> ();
            foreach (Transform transform in array) {
                transform.gameObject.layer = layer;
            }
        }
    }

    public static T GetComponentInParentEx<T> (this GameObject gameObject) where T : UnityEngine.Component {
        if (gameObject == null)
            return null;
        Transform parent = gameObject.transform.parent;
        if (parent != null) {
            T t = parent.GetComponent<T> ();
            if (t != null)
                return t;
            return parent.gameObject.GetComponentInParentEx<T> ();
        }

        return null;
    }

}